import { useState, useEffect } from 'react'
import '../../src/assets/css/cart.css'
import '../assets/js/rem'
import { getCart, getCartdelete } from '../request/api'
import { List, SwipeAction } from 'antd-mobile'
import { useNavigate, Link } from 'react-router-dom'


function Cart() {
    let Navigate = useNavigate()
    // 全选
    let [allCheck, allchange] = useState(false)
    //       购物车列表
    let [Cartlists, Usecart] = useState([])
    // 总价
    let [allPrice, allPrices] = useState('0')
    

    useEffect(() => {
        if (!JSON.parse(sessionStorage.getItem('userinfo'))) {
            alert("去登录")
            Navigate('/login')
            return
        }
        getCart({
            uid: JSON.parse(sessionStorage.getItem('userinfo')).uid
        })
            .then(res => {
                if (res.data.code == 200) {
                    if (res.data.type==1||res.data.type==2) {
                        Usecart(res.data.list[1].content||[])
                    }else{
                        Usecart(res.data.list[0].content||[])
                    }
                }
                console.log(res,'购物车')
            })
    }, [])
    useEffect(() => {

        // 合计金额
        price()
    })
    // 价格
    function price() {
        let sum = 0;
        Cartlists.map(item => {
            // console.log(item,'111');
            // console.log(item.okcheck,'222');
            if (item.okcheck) {
                sum += item.price * item.num;
            }
        })
        allPrices(sum.toFixed(2))
    }
    // 全选事件
    function changAll() {
    //     //点击按钮取反变成true
        allchange(!allCheck)
        Cartlists.map(item => {
            item.okcheck = !allCheck
        });
        Usecart([...Cartlists])
    }
    // // 单选事件
    function changone(i) {
        Cartlists[i].okcheck = !Cartlists[i].okcheck
        // console.log(Cartlists[i].okcheck);
        let arr = Cartlists.every(item => item.okcheck)
        allchange(arr)
        Usecart([...Cartlists])
    }
    // 点击删除事件
    function del(id) {
        console.log(id, '111');
        alert("删除成功")
        getCartdelete({
            id
        }).then(res => {
            console.log(res, '@@@');
        })
     
        getCart({
            uid: JSON.parse(sessionStorage.getItem('userinfo')).uid
        })
            .then(res => {
                if (res.data.code == 200) {
                    Usecart(res.data.list[0].content||[])
                }
                console.log(res,'购物车')
            })
    }
    // 点击删除事件
    //    function del(id) {

    //     alert("删除成功")
    //     Cartdelete({
    //            id
    //     }).then(res => {
    //         getCart({
    //             uid: JSON.parse(sessionStorage.getItem('islogin')).uid
    //      })
    //             .then(res => {
    //                    if (res.code == 200) {
    //                           console.log(res, '购物车');
    //                           Usecart([...res.list[1].content])
    //                    }
    //             })
    //     })

    //  }
    //       结算
    function jiesuan(e) {
        console.log(e, '结算');
        //    判断用户是否选择了一件商品
        if (Cartlists.some(item => item.okcheck)) {
            // //      some一真为真 全假为假‘
            // 先获取用户购买的数量
            let num = 0;
            // 获取用户选择的商品id
            let val = "";
            // 用户选择的购物车列表
            let goodsDetail = [];
            Cartlists.map(item => {
                if (item.okcheck) {
                    //    计算数量和
                    num += item.num
                    // id的拼接
                    val += `,${item.id}`
                    //       把选择的购物车列表推送
                    goodsDetail.push(item)
                }
            });
            // 定义一个对象去接受几个必要的参数
            let objInfo = {
                countmoney: allPrice,
                countnumber: toString(num),
                idstr: val.slice(1),
            }
            // 把获取的订单对象存到本地
            sessionStorage.setItem("objInfo", JSON.stringify(objInfo))
            // 把选择的购物车列表数组加入到本地
            sessionStorage.setItem("goodsDetail", JSON.stringify(goodsDetail))
            console.log(objInfo);
            Navigate('/oreder')
        } else {
            alert("至少选择一件商品");
        }
    }
    // 加   
    function jia(i) {
        console.log(i, '下标');
        Cartlists[i].num++;
        Usecart([...Cartlists])
    }
    // 减
    function jian(i) {
        console.log(i, '下标');
        // 判断数量不能小于1
        if (Cartlists[i].num <= 1) {
            Cartlists[i].num = 1;
        } else {
            Cartlists[i].num--;
        }
        Usecart([...Cartlists])
    }

    return (
        <div id='page'>

            <header>
                <div className="tu_box">
                    {/* <!-- 左箭头图标 --> */}
                    <span className="iconfont icon-arrow-right"></span>
                    <h2>购物车</h2>
                    <div>
                    </div>
                </div>
                <ul>
                    <li className="li1">
                        <p>全部(20)</p>
                        <hr />
                    </li>
                    <li>降价(4)</li>
                    <li>常卖(2)</li>
                    <li className="li2">
                        <span>分类</span> <i className="iconfont icon-shangxiajiantou"></i>
                    </li>
                </ul>
            </header>
            <div className='content'>

                <form action="" className="box2">
                    <ul>
                        <li className="li1">

                            <span>小U自营</span>
                        </li>
                        <li className="li2">
                            <span>以免运费</span>
                            <span>|</span>
                            <span> <a href="">领劵</a></span>
                        </li>
                    </ul>
                </form>
               
                <ul className="box2_2">
                    {Cartlists.map((item, idx) => {
                        return (
                            <li key={item.id} className='ol'>

                                <List>
                                    <SwipeAction
                                        // ref={ref}
                                        // closeOnAction={false}
                                        // closeOnTouchOutside={false}
                                        rightActions={[
                                            {
                                                key: 'delete',
                                                text: '删除',
                                                color: 'danger',

                                            },

                                        ]}
                                        onAction={() => del(item.id)}
                                    >

                                        <ol className='ol'>
                                            <li className="li1">
                                                <input
                                                    className='inp'
                                                    type="checkbox"
                                                    onChange={() => changone(idx)}
                                                    checked={item.okcheck || ""}
                                                />



                                            </li>
                                            <li className="li2">
                                                <img src={item.img} alt="" />
                                            </li>
                                            <li className="li3">
                                            <h2>{item.goodsname}</h2>

                                            <p className="p1">敏感肌可用，控油祛痘、男女可...</p>
                                                <select >
                                                    <option value="0">粉色50ML</option>
                                                    <option value="1">红色色50ML</option>
                                                    <option value="2">白色50ML</option>
                                                    <option value="3">黑色50ML</option>
                                                    <option value="4">粉色50ML</option>
                                                </select>
                                                <p className="p2">比加入时降低￥100</p>
                                                <span className="span1">￥{(item.price*item.num).toFixed(2)}</span>

                                                <span className='yuan'>￥{item.price}</span>
                                                <div className='span2'>
                                                    <i className="iconfont icon--hao" onClick={() => jian(idx)}>
                                                        <button>-</button></i>
                                                    <span>{item.num}</span>
                                                    <i className="iconfont icon-hao" onClick={() => jia(idx)}>
                                                    <button>+</button></i>
                                                </div>
                                            </li>
                                        </ol>


                                    </SwipeAction>
                                </List>
                            </li>
                        )
                    })}

                </ul>
                
            </div>
            <form action="">
                <div className="dibu">
                    <ol>
                        <li>
                            <input type="checkbox"
                                onChange={() => changAll()}
                                checked={allCheck || ""} value="" />
                            <span>全选</span>
                        </li>
                        <li>
                            <span>合计</span>
                            <p>已免运费</p>
                        </li>
                        <li>
                            <span>￥{allPrice}</span>
                        {console.log(allPrice)}
                            <p>已优惠￥200元</p>
                        </li>
                        <li>
                            <button onClick={(e) => jiesuan(e)}>
                                结算
                            </button>
                        </li>
                    </ol>
                </div>
            </form>
        </div>
    )
}
export default Cart
